package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhentao.mapper.ProductDetailsMapper;
import com.zhentao.mapper.ProductMapper;
import com.zhentao.mapper.ProductSkuMapper;
import com.zhentao.model.dto.product.ProductDto;
import com.zhentao.model.entity.product.Product;
import com.zhentao.model.entity.product.ProductDetails;
import com.zhentao.model.entity.product.ProductSku;
import com.zhentao.model.vo.common.Result;
import com.zhentao.model.vo.common.ResultCodeEnum;

import com.zhentao.service.FileStorageService;
import com.zhentao.service.ProductService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements ProductService{

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    //    minio注入配置
    @Resource
    private FileStorageService fileStorageService;

    @SneakyThrows
    @Override
    public String file(MultipartFile file) {
        if(file==null || file.getSize()<0){
            return "";
        }
        String s = fileStorageService.uploadPicFile(file.getOriginalFilename(), file.getInputStream());
        return s;
    }


    @Override
    public PageInfo<Product> findByPage(Integer page, Integer limit, ProductDto productDto) {
        PageHelper.startPage(page, limit);
        List<Product> byPage = productMapper.findByPage(productDto);
        return new PageInfo<>(byPage);
    }

    @Transactional
    @Override
    public Result productSave(Product product) {
        // 生成随机两位数的 id
        String randomId;
        Random random = new Random();
        do {
            int randomNum = random.nextInt(90) + 10; // 生成 10 - 99 的随机数
            randomId = String.valueOf(randomNum);
        } while (productMapper.existsById(randomId)); // 检查 id 是否已存在
        // 设置随机生成的 id
        product.setId(Long.valueOf(randomId));
        // 添加商品信息
        product.setAuditStatus(0);
        product.setStatus(0);
        product.setCreateTime(new Date());
        product.setIsDeleted(0);
        productMapper.save(product);
        // 保存商品 sku 数据
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (productSkuList != null &&!productSkuList.isEmpty()) {
            for (int i = 0, size = productSkuList.size(); i < size; i++) {
                ProductSku productSku = productSkuList.get(i);
                // 构建 skuCode
                productSku.setSkuCode(product.getId() + "_" + i);
                // 设置商品 id
                productSku.setProductId(product.getId());
                productSku.setSkuName(product.getName() + productSku.getSkuSpec());
                // 设置销量
                productSku.setSaleNum(0);
                productSku.setStatus(0);
                // 保存数据
                productSkuMapper.insert(productSku);
            }
        }
        // 保存商品详情数据
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(product.getId());
        productDetails.setImageUrls(product.getDetailsImageUrls());
        productDetailsMapper.insert(productDetails);
        return Result.build("添加成功", ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result productFindOne(Long id) {

//        Product product = productMapper.selectJoinOne(Product.class, new MPJLambdaWrapper<Product>()
//                .selectAll(Product.class)
//                .apply("LEFT JOIN brand b ON b.id = product.brand_id")
//                .apply("LEFT JOIN category c1 ON c1.id = product.category1_id")
//                .apply("LEFT JOIN category c2 ON c2.id = product.category2_id")
//                .apply("LEFT JOIN category c3 ON c3.id = product.category3_id")
//                .eq(Product::getId, id)
//        );
        //        查询单条商品信息
//        Product product = productMapper.selectById(id);
//        System.out.println(product);
//
//
////          查询商品规格信息（sku）
//        List<ProductSku> productSkuList = product.getProductSkuList();
//
//        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(ProductSku::getProductId, id);
//        ProductSku productSku = productSkuMapper.selectOne(wrapper);
//
//        product.setProductSkuList(productSkuList);
////        查询商品详情信息
//        LambdaQueryWrapper<ProductDetails> eq = new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id);
//        ProductDetails productDetails = productDetailsMapper.selectOne(eq);
//        product.setDetailsImageUrls(productDetails.getImageUrls());



        // 根据id查询商品数据
        Product product = productMapper.selectById(id);

        // 根据商品的id查询sku数据
        List<ProductSku> productSkuList = productSkuMapper.selectByProductId(id);
        if(productSkuList != null && !productSkuList.isEmpty()){
            product.setProductSkuList(productSkuList);
        }


        // 根据商品的id查询商品详情数据
        ProductDetails productDetails = productDetailsMapper.selectByProductId(product.getId());
        if (productDetails != null){
            product.setDetailsImageUrls(productDetails.getImageUrls());
        }


        return Result.build(product, ResultCodeEnum.SUCCESS);
    }

    @Transactional
    @Override
    public Result productUpdate(Product product) {
//        //修改商品的基本信息
//        product.setUpdateTime(new Date());
//        productMapper.updateById(product);
//        //修改商品规格（sku）数据
//        List<ProductSku> productSkuList = product.getProductSkuList();
//        if (productSkuList != null && !productSkuList.isEmpty()) {
//            for (ProductSku productSku : productSkuList) {
//                productSkuMapper.updateById(productSku);
//            }
//        }
//        //修改商品的详情数据
//        LambdaQueryWrapper<ProductDetails> eq = new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId());
//        ProductDetails productDetails = productDetailsMapper.selectOne(eq);
//        productDetailsMapper.updateById(productDetails);


        // 修改商品基本数据
        productMapper.updateById(product);

        // 修改商品的sku数据
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (productSkuList != null && !productSkuList.isEmpty()){
            productSkuList.forEach(productSku -> {
                productSkuMapper.update(productSku,new LambdaUpdateWrapper<ProductSku>().eq(ProductSku::getProductId,product.getId()));
            });
        }

        // 修改商品的详情数据
        ProductDetails productDetails = productDetailsMapper.selectByProductId(product.getId());
        productDetails.setImageUrls(product.getDetailsImageUrls());
        productDetailsMapper.updateById(productDetails);
        return Result.build("操作成功", ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result productDelete(Long id) {

//        删除商品的单条信息
        int i = productMapper.deleteById(id);
        System.out.println(i+"+++++++++++++++++++++++++++++++");
        //删除相关的商品详情的信息
        LambdaQueryWrapper<ProductDetails> eq = new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id);
        int delete = productDetailsMapper.delete(eq);
        System.out.println("------------------");
        //删除相关的商品规格信息
        LambdaQueryWrapper<ProductSku> eq1 = new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id);
        int delete1 = productSkuMapper.delete(eq1);
        System.out.println(delete1+"*******************");
        return Result.build("操作成功", ResultCodeEnum.SUCCESS);
    }

    // com.zt.ztzx.manager.service.impl;
    @Override
    public Result updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if(auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批不通过");
        }
        productMapper.updateById(product);

        return Result.build("操作成功", ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        if(status == 1) {
            product.setStatus(1);
        } else {
            product.setStatus(-1);
        }
        productMapper.updateById(product);
        return Result.build("操作成功", ResultCodeEnum.SUCCESS);

    }
}
